package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

//初始化布隆过滤器
@Configuration
public class BloomFilterConfig {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private GmallPmsClient gmallPmsClient;

    private static final String KEY_PREFIX = "index:cates:";

    @Bean
    public RBloomFilter bloomFilter(){
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("index:bf");
        bloomFilter.tryInit(2000,0.03);
        //初始化布隆过滤器的数据
        // 三级分类 需要根据查询的一级分类的id查询 将一级分类的id放入布隆过滤器中
        ResponseVo<List<CategoryEntity>> responseVo= gmallPmsClient.getInfoByParentId(0L);
        List<CategoryEntity> categoryEntities = responseVo.getData();
        if (!CollectionUtils.isEmpty(categoryEntities)){
            categoryEntities.forEach(categoryEntity -> {
                bloomFilter.add(KEY_PREFIX+categoryEntity.getId());
            });
        }

        //TODO:广告数据也需要放入布隆过滤器
        return bloomFilter;
    }
}
